package com.example.common.utils;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.text.TextUtils;

import com.example.common.R;

import java.util.List;


/**
 * @author skygge
 * @date 2020/5/16.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：跳转国内应用市场
 */
public class AppMarketUtil {
    //GooglePlay
    private static final String PACKAGE_GOOGLE_MARKET = "com.android.vending";

    //应用宝
    private static final String PACKAGE_TENCENT_MARKET = "com.tencent.android.qqdownloader";
    private static final String TENCENT_MARKET_PAGE = "com.tencent.pangu.link.LinkProxyActivity";

    //华为应用商店
    private static final String PACKAGE_HUAWEI_MARKET = "com.huawei.appmarket";
    private static final String HUAWEI_MARKET_PAGE = "com.huawei.appmarket.service.externalapi.view.ThirdApiActivity";

    //小米应用商店
    private static final String PACKAGE_MI_MARKET = "com.xiaomi.market";
    private static final String MI_MARKET_PAGE = "com.xiaomi.market.ui.AppDetailActivity";

    /**** 以下三个商店未上架 预留出接口 ****/
    //魅族应用商店
    private static final String PACKAGE_MEIZU_MARKET = "com.meizu.mstore";
    private static final String MEIZU_MARKET_PAGE = "com.meizu.flyme.appcenter.activitys.AppMainActivity";
    //VIVO应用商店
    private static final String PACKAGE_VIVO_MARKET = "com.bbk.appstore";
    private static final String VIVO_MARKET_PAGE = "com.bbk.appstore.ui.AppStoreTabActivity";
    //OPPO应用商店
    private static final String PACKAGE_OPPO_MARKET = "com.oppo.market";
    private static final String OPPO_MARKET_PAGE = "a.a.a.aoz";

    /**
     * 进入国内应用市场详情页
     * @param context
     */
    public static void gotoChinaMarket(Context context) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + getPackageName(context)));
        String[] keys = getKeys(context);
        if (keys != null) {
            intent.setClassName(keys[0], keys[1]);
        }
        //修复某些老手机会因为找不到任何市场而报错
        if (isIntentAvailable(context, intent)) {
            context.startActivity(intent);
        } else {
            CustomToastUtil.showToast(context, context.getString(R.string.currently_the_latest_version));
        }
    }

    /**
     * 进入GooglePlay商店详情页
     * @param context
     */
    public static void gotoGoogleMarket(Context context) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=" + getPackageName(context)));
            intent.setPackage(PACKAGE_GOOGLE_MARKET);//这里对应的是谷歌商店，跳转别的商店改成对应的即可
            if (intent.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(intent);
            } else {//没有应用市场，通过浏览器跳转到Google Play
                Intent intent2 = new Intent(Intent.ACTION_VIEW);
                intent2.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName(context)));
                if (intent2.resolveActivity(context.getPackageManager()) != null) {
                    context.startActivity(intent2);
                } else {
                    //没有Google Play 也没有浏览器
                    CustomToastUtil.showToast(context, context.getString(R.string.currently_the_latest_version));
                }
            }
        } catch (ActivityNotFoundException activityNotFoundException1) {
            CustomToastUtil.showToast(context, context.getString(R.string.currently_the_latest_version));
        }
    }

    private static String[] getKeys(Context context) {
        String[] keys = new String[2];
        if (isPackageExist(context, PACKAGE_TENCENT_MARKET)) {
            keys[0] = PACKAGE_TENCENT_MARKET;
            keys[1] = TENCENT_MARKET_PAGE;
        } else if (isPackageExist(context, PACKAGE_HUAWEI_MARKET)) {
            keys[0] = PACKAGE_HUAWEI_MARKET;
            keys[1] = HUAWEI_MARKET_PAGE;
        } else if (isPackageExist(context, PACKAGE_MI_MARKET)) {
            keys[0] = PACKAGE_MI_MARKET;
            keys[1] = MI_MARKET_PAGE;
        } else if (isPackageExist(context, PACKAGE_VIVO_MARKET)) {
            keys[0] = PACKAGE_VIVO_MARKET;
            keys[1] = VIVO_MARKET_PAGE;
        } else if (isPackageExist(context, PACKAGE_OPPO_MARKET)) {
            keys[0] = PACKAGE_OPPO_MARKET;
            keys[1] = OPPO_MARKET_PAGE;
        } else if (isPackageExist(context, PACKAGE_MEIZU_MARKET)) {
            keys[0] = PACKAGE_MEIZU_MARKET;
            keys[1] = MEIZU_MARKET_PAGE;
        }
        if (TextUtils.isEmpty(keys[0])) {
            return null;
        } else {
            return keys;
        }
    }

    /**
     * 获取app包名
     *
     * @return 返回包名
     */
    public static String getPackageName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            return info.packageName;
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }
    }

    /**
     * @param context
     * @param packageName
     * @return
     * @Title isPackageExist
     * @Description .判断package是否存在
     */
    @SuppressLint("WrongConstant")
    public static boolean isPackageExist(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        Intent intent = new Intent().setPackage(packageName);
        List<ResolveInfo> info = manager.queryIntentActivities(intent,
                PackageManager.GET_INTENT_FILTERS);
        if (info == null || info.size() < 1) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 检测 响应某个Intent的Activity 是否存在
     * @param context
     * @param intent
     * @return
     */
    @SuppressLint("WrongConstant")
    public static boolean isIntentAvailable(Context context, Intent intent) {
        final PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        return list.size() > 0;
    }

}
